// 设置登录和登出模块的js  
var userData = $.cookie("userState");
console.log(userData)
userData = userData? JSON.parse(userData):null;
if(userData && userData.state ===1){
    $(".index-login").hide();
    $(".welcome").show().children("span").text(userData.user);
}else{
 $(".index-login").show();
 $(".welcome").hide();
}
$(".welcome").children("i").click(function(){
    userData.state = 0;
    $.cookie("userState",JSON.stringify(userData));
    location.reload();
})
//分页模块
function Page(ops = {}){
    this.url = ops.url;
    this.index = ops.index || 0;//页码的默认
    this.num = ops.num || 4;
    this.pageCont = ops.pageCont;
    this.listCont = ops.listCont;
    this.seven = $(".list").find("figure").eq(1).children("figcaption").children("span").eq(2)[0];
    this.load();
    
    this.addEvent();
}
Page.prototype = {
    constructor:Page,
    load(){
        $.ajax({
            url:this.url,
            data:{
                type:"goods",
            },
            success:res=>{
                res = JSON.parse(res)[3];
                this.creatPage(res);
            }
        });
        cartNum();
    },
    addEvent:function(){
        var that = this;
        this.seven.onclick = function(){
            $.ajax({
                url:"http://localhost:3000/api",
                data:{
                    type:"goods",
                },
                success:function(res){
                    res = JSON.parse(res)[3];
                    var res1=[];
                    res.forEach(element => {
                        if(element.折扣>0.7){
                            res1.push(element)
                        }
                    });
                    // console.log(res1);
                    that.creatPage(res1);
                }
            })
        };
        
    },
    creatPage(res){
        var that = this;
        this.pageCont.pagination(res.length,{
            items_per_page:this.num,
            current_page:this.index,
            prev_text:"上一页",
            next_text:"下一页",
            callback(i){
                that.index = i ;//这里的i是当前页码的索引
                that.render(res);
            }//this指向分页的实例

        })
    },
    render(res){
        var str ="";
        for(var i=this.index*this.num;i<this.index*this.num+this.num;i++){//遍历当前页码的数据，i表示res中数据的索引
            if(i<res.length){
                str +=`<div class="item">
                <div class="item-img">
                    <a href="details.html?id=${res[i].id}"><img src="https://dummyimage.com/160x160/ccc/fff" data-src="${res[i].图片地址}" alt=""></a>
                </div>
                <article>
                    <h3><a href="##">${res[i].书名}</a></h3>
                    <p><b>${res[i].现价}</b>&nbsp;&nbsp;&nbsp;定价&nbsp;&nbsp;<span>${res[i].定价}</span><i>（${res[i].折扣}折）</i></p>
                    <p><span>作者：</span><a href="##">${res[i].作者}</a> </p>
                    <p>出版社：<a href="##">${res[i].出版社}</a></p>
                    <p>出版时间：<span>${res[i].出版时间}</span></p>
                    <p>顾客评价：<span></span></p>
                </article>
                <aside data-index=${res[i].id}>
                    <p class="add" ></p>
                    <p></p>
                </aside>
            </div>`;
            }
        }
        this.listCont.html(str);
        lazy();
    }
}
new Page({
    url:"http://localhost:3000/api",
    index:0,
    num:5,
    pageCont:$(".pagination"),
    listCont:$(".cont")
});

//添加cookie
class List{
    constructor(){
        this.cont = $(".cont");
        this.url = "http://localhost:3000/api";
        this.addEvent();//添加点击事件（添加到购物车）
    }
    addEvent(){
        // console.log(this)
        this.cont[0].addEventListener("click",function(eve){
            if(eve.target.className==="add"){
                this.id = eve.target.parentNode.getAttribute("data-index");//获取数据库中商品唯一id，也就是value.Id
                this.setData();
                cartNum()
            }
        }.bind(this))
    }
    setData(){
        this.data = $.cookie("goodMsg")? JSON.parse($.cookie("goodMsg")) : [] ;
        // console.log(this.data);
        if(this.data.length<1){
            this.data.push({
                id:this.id,
                num:1
            })//把数据存进数组，并不是存进cookie
        }else{
            let i = 0;
            let onoff= this.data.some((val,idx,)=>{
                i = idx;
                return val.id === this.id;
            });
            if(onoff){
                this.data[i].num++;
            }else{
                this.data.push({
                    id:this.id,//this.id保存了数据库中唯一Id的信息
                    num:1,
                })
            }
        }
         
        $.cookie("goodMsg",JSON.stringify(this.data));
    }
}
new List();
// 懒加载
function lazy(){
    var aimg = $(".cont").find("img");
    var arr = Array.from(aimg);
    var clientH = document.documentElement.clientHeight;
    function fn(){
        var scrollT = document.documentElement.scrollTop; 
        for(var i=0;i<arr.length;i++){
            if(scrollT + clientH > arr[i].offsetTop - 100){
                arr[i].src = arr[i].getAttribute("data-src");
                arr.splice(i, 1);
                i--;
            }
        }
    }

    fn();

    var j = 0;     
    onscroll = function(){
        j++;    
        if(j%10 == 0){  
           
            fn();
        }
    }

}


function cartNum(){
    var Num=0;
    JSON.parse($.cookie("goodMsg")).forEach(element => {
        console.log(element.num)
        Num+=element.num;
    });
    $(".search-wrap-wrap .cart").find("i").html(Num);

}


